import tushare as ts
import numpy as np


# 获得上一次开市的日期
# 形参为今日日期date, date为格式为"YYYYMMDD"格式字符串
def get_previous_trading_day(date):
    ts.set_token('b2109fc6949181eb2f598eae02f4de44e028e7eb20ffc39503a7fd9e')
    pro = ts.pro_api()
    df_por = np.array(pro.trade_cal(exchange="SSE", end_date=date))
    result = ''
    i = len(df_por) - 2
    while i >= 0:
        if df_por[i][2] == 1:
            result = df_por[i][1]
            break
        i -= 1
    return result


# 获取股票名称
# 形参为股票代码
def get_stock_name(ts_code): #获取股票名称 形参为股票代码
    ts.set_token('b2109fc6949181eb2f598eae02f4de44e028e7eb20ffc39503a7fd9e')
    pro = ts.pro_api()
    temp_ts_code = ts_code[-2:]
    if temp_ts_code == "SH":
        return pro.stock_basic(exchange="SSE", ts_code=ts_code)['name']
    else:
        return pro.stock_basic(exchange="SZSE", ts_code=ts_code)['name']


# 判断date这一天是否开市，date格式“YYYYMMDD”
# True为开市，False为不开市
def is_open(date):
    ts.set_token('b2109fc6949181eb2f598eae02f4de44e028e7eb20ffc39503a7fd9e')
    pro = ts.pro_api()
    df = np.array(pro.trade_cal(exchange="SSE", start_date=date))
    if df[0][2] == 1:
        return True
    else:
        return False


# 获取当前股票当天的收盘价,date类型“YYYYMMDD”
def get_sell_price(ts_code, date):
    ts.set_token('b2109fc6949181eb2f598eae02f4de44e028e7eb20ffc39503a7fd9e')
    pro = ts.pro_api()
    df = pro.daily(ts_code=ts_code, trade_date=date)
    # print(df)
    return df['close'][0]


# 获取全部退市股票基础信息
# data = pro.stock_basic(ts_code="000001.SZ")
if __name__ == "__main__":
    # res = get_previous_trading_day("20210521")
    # print(res)
    # name = get_stock_name("000585.SZ")
    # print(is_open("20210521"))
    # print(res)
    print(get_sell_price("000001.SZ", "20210521"))

